package org.jeecg.modules.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.jeecg.modules.entity.InterfaceInfo;
import org.jeecg.modules.mapper.InterfaceInfoMapper;
import org.jeecg.modules.service.IInterfaceInfoService;
import org.jeecg.modules.utils.ApiUtil;
import org.jeecg.modules.utils.DateUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 接口返回数据
 * @Author: jeecg-boot
 * @Date:   2023-02-20
 * @Version: V1.0
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo> implements IInterfaceInfoService {

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    @Override
    public Map<String,String> selectInterfaceInfo(String content, Map<String, String> urlMap, Map<String, String> map) {
        Map<String,String> analysisStr = new HashMap<>();
        try{
            //查询今日是否调用过
            Map<String ,Object> searchMap = new HashMap<>();
            searchMap.put("path",urlMap.get("url")+"&"+content);
            searchMap.put("time",DateUtil.toStringInYearMonthDayPattern(new Date()));
            List<InterfaceInfo> interfaceInfos = interfaceInfoMapper.selectInterfaceInfoInDaay(searchMap);
            if(interfaceInfos.size()==0){
                //调用接口
                InputStream link = ApiUtil.createLink(urlMap, content);
                //格式化返回数据
                analysisStr = ApiUtil.analysisStr(link);
                // 保存请求结果
                InterfaceInfo interfaceInfo = new InterfaceInfo();
                interfaceInfo.setPath(urlMap.get("url")+"&"+content);
                interfaceInfo.setResult(JSON.toJSONString(analysisStr));
                interfaceInfoMapper.insert(interfaceInfo);
            }else{
                Gson gson = new Gson();
                analysisStr = gson.fromJson(interfaceInfos.get(0).getResult(), map.getClass());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return analysisStr;
    }
}
